﻿using MediatR;
using W.Purchase.API.Application.Command.ProcurementCommand;
using W.Purchase.Repository.Interface;

namespace W.Purchase.API.Application.CommandHandler.ProcurementCommandHandler
{
    public class ProcurementDeleteRangeCommandHandler : IRequestHandler<ProcurementDeleteRangeCommand, ApiResult<int>>
    {
        private readonly ILogger<ProcurementDeleteRangeCommandHandler> _logger;
        private readonly IProcurementRepository _procurementRepository;
        private readonly IBuyProductsRepository _buyProductsRepository;
        public ProcurementDeleteRangeCommandHandler(ILogger<ProcurementDeleteRangeCommandHandler> logger, IProcurementRepository procurementRepository, IBuyProductsRepository buyProductsRepository)
        {
            _logger = logger;
            _procurementRepository = procurementRepository;
            _buyProductsRepository = buyProductsRepository;
        }
        public async Task<ApiResult<int>> Handle(ProcurementDeleteRangeCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            try
            {
                var list = await _buyProductsRepository.GetAllAsaync();
                var blist = list.Where(c => request.buyProductsId.Contains(c.BuyProductsId)).ToList();
                foreach (var item in blist)
                {
                    item.IsDelete = true;
                    item.DeleteTime = DateTime.Now;
                }
                result.Code = await _buyProductsRepository.UpdateRangeAsync(blist);
                _logger.LogInformation("批量删除采购管理成功");
            }
            catch (Exception el)
            {
                result.Code = -1;
                result.Message = el.Message;
                _logger.LogError(el, el.Message);
                //throw;
            }
            return result;
        }
    }
}
